package com.df.gameserver.net;

import com.df.MsgInfo;
import com.df.gameserver.modules.user.UserManager;
import com.df.gameserver.modules.user.entity.Player;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import com.manager.MsgManager;
import io.netty.channel.Channel;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


public class MsgSend {

    public static void send(Channel ctx, GeneratedMessageV3.Builder builder) {
        Message msg = builder.build();
        MsgInfo info = new MsgInfo();
        info.setMsgId(MsgManager.getInstance().getMsgId((Class<? extends GeneratedMessageV3>) msg.getClass()));
        byte[] dataBytes = msg.toByteArray();
        info.setData(dataBytes);
        ctx.writeAndFlush(info);
    }

    public static void broadcastAll(GeneratedMessageV3.Builder builder) {
        Message msg = builder.build();
        MsgInfo info = new MsgInfo();
        info.setMsgId(MsgManager.getInstance().getMsgId((Class<? extends GeneratedMessageV3>) msg.getClass()));
        byte[] dataBytes = msg.toByteArray();
        info.setData(dataBytes);
        sendMsg(info, null);
    }

    public static void broadcastAllUser(GeneratedMessageV3.Builder builder, List<Player> exclude) {
        Message msg = builder.build();
        MsgInfo info = new MsgInfo();
        info.setMsgId(MsgManager.getInstance().getMsgId((Class<? extends GeneratedMessageV3>) msg.getClass()));
        byte[] dataBytes = msg.toByteArray();
        info.setData(dataBytes);
        sendMsg(info, exclude);
    }
    public static void broadcastAll(GeneratedMessageV3.Builder builder, List<String> exclude) {
        Message msg = builder.build();
        MsgInfo info = new MsgInfo();
        info.setMsgId(MsgManager.getInstance().getMsgId((Class<? extends GeneratedMessageV3>) msg.getClass()));
        byte[] dataBytes = msg.toByteArray();
        info.setData(dataBytes);
        sendMsgDo(info, exclude);
    }

    public static void sendMsg(MsgInfo info, List<Player> excludePlayers) {
        List<String> collect = excludePlayers.stream().map(player -> player.getId()).collect(Collectors.toList());
        sendMsgDo(info, collect);

    }

    public static void sendMsgDo(MsgInfo info, List<String> excludeUserIds) {
        Collection<Channel> usersChannels = UserManager.getInstance().getId2channel().values();
        List<Channel> excludeChannels = excludeUserIds.stream().map(userId -> UserManager.getInstance().getChannel(userId)).collect(Collectors.toList());
        if (excludeUserIds != null && excludeUserIds.size() > 0) {
            usersChannels = usersChannels.stream()
                    .filter(channel -> !excludeChannels.contains(channel))
                    .collect(Collectors.toList());
        }
        for (Channel channel : usersChannels) {
            channel.writeAndFlush(info);
        }

    }
}
